package com.dqhl.smartstable.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.smartstable.R;
import com.dqhl.smartstable.base.BaseActivity;
import com.dqhl.smartstable.model.User;
import com.dqhl.smartstable.util.Config;
import com.dqhl.smartstable.util.Constant;
import com.dqhl.smartstable.util.Dlog;
import com.dqhl.smartstable.util.JPushUtil;
import com.dqhl.smartstable.util.JsonUtils;
import com.dqhl.smartstable.util.TimeCountLoginUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by cheng on 2016/10/12.
 * 登录界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private CheckBox cb_agree;
    private TextView tv_protocol; //用户协议
    private Button btn_login;
    private EditText et_phone;
    private EditText et_auth_code;
    private TextView tv_get_auth_code; //获取验证码

    private String strPhone;
    private String strCode;
    private String token;
    private String isBind;
    private String caseSN;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
    }

    private void initView() {
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_auth_code = (EditText) findViewById(R.id.et_auth_code);
        tv_get_auth_code = (TextView) findViewById(R.id.tv_get_auth_code);
        cb_agree = (CheckBox) findViewById(R.id.cb_agree);
        tv_protocol = (TextView) findViewById(R.id.tv_protocol);
        btn_login = (Button) findViewById(R.id.btn_login);

        tv_get_auth_code.setOnClickListener(this);
//        cb_agree.setOnClickListener(this);
        cb_agree.setChecked(true);
//        iv_login.setEnabled(false);
        tv_protocol.setOnClickListener(this);
        btn_login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_get_auth_code: //获取验证码
                getAuthCode();
                break;
//            case R.id.cb_agree:
//                if (cb_agree.isChecked()) {
//                    iv_login.setEnabled(true);
//                } else {
//                    iv_login.setEnabled(false);
//                }
//                break;
            case R.id.tv_protocol:
                overlay(ProtocolActivity.class);
                break;
            case R.id.btn_login:
                doLogin();
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getAuthCode() {
        TimeCountLoginUtil timeCountLoginUtil = new TimeCountLoginUtil(this,
                60000, 1000, tv_get_auth_code);
        timeCountLoginUtil.start();
        strPhone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(strPhone)) {
            toast("手机号不能为空");
        } else {
            RequestParams params = new RequestParams(Config.Api.auth_code);
            params.addBodyParameter("account", strPhone);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    String msg = JsonUtils.getMsg(result);
                    String code = JsonUtils.getCode(result);
                    if ("2000".equals(msg)) {
                        Dlog.e("code:" + code);
                    } else {
                        toast(code);
                        Dlog.e("code:" + code);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    /**
     * 登录
     */
    private void doLogin() {
        showCustomLoadBar("登录中");
        strPhone = et_phone.getText().toString().trim();
        strCode = et_auth_code.getText().toString().trim();
        if (TextUtils.isEmpty(strPhone)) {
            toast("手机号不能为空");
        } else if (TextUtils.isEmpty(strCode)) {
            toast("请输入验证码");
        } else if (!cb_agree.isChecked()) {
            toast("请先同意用户协议");
        } else {
            RequestParams params = new RequestParams(Config.Api.login);
            params.addBodyParameter("phone", strPhone);
            params.addBodyParameter("code", strCode);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    String msg = JsonUtils.getMsg(result);
                    String code = JsonUtils.getCode(result);
                    String data = JsonUtils.getData(result);
                    User user = JSON.parseObject(data, User.class);
                    token = user.getToken();
                    isBind = user.getIsbind();
                    caseSN = user.getCase_sign();
                    // 注册登录成功后,保存token,设置alias
                    if ("2000".equals(msg)) {
                        sp.edit().putString(Constant.TOKEN, token).apply();
                        setAlias(token);
                        Dlog.e(code + ";token:" + token);
                    } else {
                        Dlog.e(code);
                        toast(code);
                    }

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    /**
     * JPush设置别名
     */
    private void setAlias(String alias) {
        if (TextUtils.isEmpty(alias)) {
            toast(R.string.error_alias_empty);
            return;
        }
        if (!JPushUtil.isValidTagAndAlias(alias)) {
            toast(R.string.error_tag_gs_empty);
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Dlog.e("Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    Dlog.e("Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    sp.edit().putString(Constant.ALIAS, alias).apply();
                    Dlog.e(logs + "---alias为:" + alias);
                    if ("1".equals(isBind)) { //已绑定箱子
                        sp.edit().putString(Constant.SN, caseSN).apply();
                        Dlog.e("---caseSN为:" + caseSN);
                        forward(MainActivity.class);
                    } else if ("2".equals(isBind)) { //未绑定箱子
                        // 跳转到 绑定箱子SN码界面
                        overlay(BindingSNActivity.class);
                    }
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Dlog.e(logs);
                    if (JPushUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Dlog.e("No network");
                    }
                    toast(logs);
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Dlog.e(logs);
                    toast(logs);
            }

        }

    };
}
